package init

import (
	"appointment-srv/basic/config"
	_ "appointment-srv/basic/config"
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

func NacosInit() {
	clientConfig := constant.ClientConfig{
		NamespaceId:         config.Appnaco.NameSpace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      config.Appnaco.Host,
			ContextPath: "/nacos",
			Port:        uint64(config.Appnaco.Port),
			Scheme:      "http",
		},
	}

	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: config.Appnaco.Dataid,
		Group:  config.Appnaco.Group})
	if err != nil {
		panic(err)
	}
	json.Unmarshal([]byte(content), &config.Appnaco.Nacos)
	fmt.Println(&content)

	configClient.ListenConfig(vo.ConfigParam{
		DataId: config.Appnaco.Dataid,
		Group:  config.Appnaco.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})
}
